using Unity.Burst;
using Unity.Collections;
using Unity.Entities;
using Unity.Mathematics;
using Unity.Transforms;
using Random = Unity.Mathematics.Random;

namespace HelloCube.Prefabs
{
    public partial struct SpawnSystem : ISystem
    {
        uint mUpdateCounter;

        [BurstCompile]
        public void OnCreate(ref SystemState state)
        {
            state.RequireForUpdate<Execute.Prefabs>();
            state.RequireForUpdate<Spawner>();
        }

        [BurstCompile]
        public void OnUpdate(ref SystemState state)
        {
            //创建一个查询，匹配所有包含RotateSpeed组件的实体
            //生成查询缓存，因此不会产生每次更新都重新创建查询的开销
            var cubesQuery = SystemAPI.QueryBuilder().WithAll<RotateSpeed>().Build();

            if (cubesQuery.IsEmpty)
            {
                var prefab = SystemAPI.GetSingleton<Spawner>().Prefab;

                var instances = state.EntityManager.Instantiate(prefab, 500, Allocator.Temp);

                var random = Random.CreateFromIndex(mUpdateCounter++);

                foreach (var entity in instances)
                {
                    var transform = SystemAPI.GetComponentRW<LocalTransform>(entity); //缓存不友好的操作，性能偏低
                    transform.ValueRW.Position = (random.NextFloat3() - new float3(0.5f, 0, 0.5f)) * 20;
                }
            }
        }
    }
}